// 2D World 演示脚本
// 这个脚本展示了如何使用2D World库的各种功能

import { Circle, Line, Polygon, Rectangle } from '../src/shapes/index.js';
import World from '../src/World/World.js';

/**
 * 演示类 - 展示2D World的各种功能
 */
export class WorldDemo {
  constructor(canvas) {
    this.canvas = canvas;
    this.world = null;
    this.demoObjects = [];
    this.isRunning = false;

    this.initialize();
  }

  /**
   * 初始化演示
   */
  initialize() {
    // 创建World实例
    this.world = new World(this.canvas, {
      gridSize: 20,
      gridVisible: true,
      snapToGrid: false,
      backgroundColor: '#f8f9fa',
    });

    // 初始化World
    this.world.initialize();

    // 设置事件监听
    this.setupEventListeners();

    console.log('2D World 演示已初始化');
  }

  /**
   * 设置事件监听器
   */
  setupEventListeners() {
    // 监听对象事件
    this.world.on('objectAdded', this.onObjectAdded.bind(this));
    this.world.on('objectRemoved', this.onObjectRemoved.bind(this));
    this.world.on('selectionChanged', this.onSelectionChanged.bind(this));
    this.world.on('transformChanged', this.onTransformChanged.bind(this));
    this.world.on('viewChanged', this.onViewChanged.bind(this));
    this.world.on('historyChanged', this.onHistoryChanged.bind(this));
    this.world.on('layerChanged', this.onLayerChanged.bind(this));
  }

  /**
   * 演示1: 基本图形创建
   */
  demoBasicShapes() {
    console.log('开始演示: 基本图形创建');

    // 创建默认图层
    this.world.createLayer('demo-layer', '演示图层');
    this.world.setActiveLayer('demo-layer');

    // 创建矩形
    const rectangle = new Rectangle(
      120,
      80,
      {
        position: { x: 200, y: 200 },
        rotation: 0,
        scale: { x: 1, y: 1 },
        anchor: { x: 0.5, y: 0.5 },
      },
      {
        fillColor: '#3498db',
        strokeColor: '#2980b9',
        strokeWidth: 2,
      },
    );

    // 创建圆形
    const circle = new Circle(
      50,
      {
        position: { x: 400, y: 300 },
        rotation: 0,
        scale: { x: 1, y: 1 },
        anchor: { x: 0.5, y: 0.5 },
      },
      {
        fillColor: '#e74c3c',
        strokeColor: '#c0392b',
        strokeWidth: 2,
      },
    );

    // 创建多边形
    const polygon = new Polygon(
      [
        { x: 0, y: -40 },
        { x: 40, y: 0 },
        { x: 0, y: 40 },
        { x: -40, y: 0 },
      ],
      {
        position: { x: 600, y: 200 },
        rotation: 45,
        scale: { x: 1, y: 1 },
        anchor: { x: 0.5, y: 0.5 },
      },
      {
        fillColor: '#27ae60',
        strokeColor: '#219a52',
        strokeWidth: 2,
      },
      undefined,
      true,
    );

    // 创建线条
    const line = new Line(
      { x: -50, y: 0 },
      { x: 50, y: 0 },
      {
        position: { x: 300, y: 400 },
        rotation: 30,
        scale: { x: 1, y: 1 },
        anchor: { x: 0.5, y: 0.5 },
      },
      {
        fillColor: 'transparent',
        strokeColor: '#9b59b6',
        strokeWidth: 3,
      },
    );

    // 添加到World
    this.world.addObject(rectangle);
    this.world.addObject(circle);
    this.world.addObject(polygon);
    this.world.addObject(line);

    this.demoObjects.push(rectangle, circle, polygon, line);

    console.log('基本图形创建演示完成');
  }

  /**
   * 演示2: 选择与变换
   */
  demoSelectionAndTransform() {
    console.log('开始演示: 选择与变换');

    if (this.demoObjects.length === 0) {
      console.warn('请先运行基本图形创建演示');
      return;
    }

    // 选择所有对象
    this.demoObjects.forEach((obj) => {
      this.world.select(obj, true);
    });
    console.log('已选择所有演示对象');

    // 演示移动
    setTimeout(() => {
      this.world.translateSelected({ x: 50, y: 30 });
      console.log('对象已移动');
    }, 1000);

    // 演示旋转
    setTimeout(() => {
      this.world.rotateSelected(Math.PI / 4);
      console.log('对象已旋转45度');
    }, 2000);

    // 演示缩放
    setTimeout(() => {
      this.world.scaleSelected(1.2, 1.2);
      console.log('对象已缩放120%');
    }, 3000);

    // 清空选择
    setTimeout(() => {
      this.world.clearSelection();
      console.log('选择已清空');
    }, 4000);
  }

  /**
   * 演示3: 图层管理
   */
  demoLayerManagement() {
    console.log('开始演示: 图层管理');

    // 创建多个图层
    this.world.createLayer('background-layer', '背景图层');
    this.world.createLayer('foreground-layer', '前景图层');

    // 在背景图层创建对象
    this.world.setActiveLayer('background-layer');
    const bgRect = new Rectangle(
      300,
      200,
      {
        position: { x: 400, y: 300 },
        rotation: 0,
        scale: { x: 1, y: 1 },
        anchor: { x: 0.5, y: 0.5 },
      },
      {
        fillColor: '#ecf0f1',
        strokeColor: '#bdc3c7',
        strokeWidth: 1,
      },
    );

    this.world.addObject(bgRect);

    // 在前景图层创建对象
    this.world.setActiveLayer('foreground-layer');
    const fgCircle = new Circle(
      40,
      {
        position: { x: 400, y: 300 },
        rotation: 0,
        scale: { x: 1, y: 1 },
        anchor: { x: 0.5, y: 0.5 },
      },
      {
        fillColor: '#e74c3c',
        strokeColor: '#c0392b',
        strokeWidth: 2,
      },
    );

    this.world.addObject(fgCircle);

    // 演示图层可见性控制
    setTimeout(() => {
      this.world.setLayerVisibility('background-layer', false);
      console.log('背景图层已隐藏');
    }, 1000);

    setTimeout(() => {
      this.world.setLayerVisibility('background-layer', true);
      console.log('背景图层已显示');
    }, 2000);

    console.log('图层管理演示完成');
  }

  /**
   * 演示4: 撤销重做
   */
  demoUndoRedo() {
    console.log('开始演示: 撤销重做');

    // 创建一些操作
    const testObject = new Rectangle(
      60,
      40,
      {
        position: { x: 100, y: 100 },
        rotation: 0,
        scale: { x: 1, y: 1 },
        anchor: { x: 0.5, y: 0.5 },
      },
      {
        fillColor: '#f39c12',
        strokeColor: '#d68910',
        strokeWidth: 2,
      },
    );

    this.world.addObject(testObject);

    // 演示一系列操作
    setTimeout(() => {
      this.world.select(testObject);
      this.world.translateSelected({ x: 100, y: 0 });
      console.log('操作1: 对象已移动');
    }, 500);

    setTimeout(() => {
      this.world.rotateSelected(Math.PI / 6);
      console.log('操作2: 对象已旋转30度');
    }, 1000);

    setTimeout(() => {
      this.world.scaleSelected(1.5, 1.5);
      console.log('操作3: 对象已缩放150%');
    }, 1500);

    // 演示撤销
    setTimeout(() => {
      this.world.undo();
      console.log('撤销: 缩放操作已撤销');
    }, 2000);

    setTimeout(() => {
      this.world.undo();
      console.log('撤销: 旋转操作已撤销');
    }, 2500);

    // 演示重做
    setTimeout(() => {
      this.world.redo();
      console.log('重做: 旋转操作已重做');
    }, 3000);

    setTimeout(() => {
      this.world.redo();
      console.log('重做: 缩放操作已重做');
    }, 3500);

    console.log('撤销重做演示完成');
  }

  /**
   * 演示5: 序列化与反序列化
   */
  demoSerialization() {
    console.log('开始演示: 序列化与反序列化');

    // 序列化当前场景
    const worldData = this.world.serialize();
    console.log('场景已序列化:', worldData);

    // 保存到本地存储
    localStorage.setItem('demo-world-data', JSON.stringify(worldData));
    console.log('场景数据已保存到本地存储');

    // 演示从数据恢复
    setTimeout(() => {
      // 清空当前场景
      const objects = this.world.getObjects();
      objects.forEach((obj) => {
        this.world.removeObject(obj);
      });

      // 从本地存储加载
      const savedData = localStorage.getItem('demo-world-data');
      if (savedData) {
        const worldData = JSON.parse(savedData);
        this.world.deserialize(worldData);
        console.log('场景已从本地存储恢复');
      }
    }, 2000);

    console.log('序列化演示完成');
  }

  /**
   * 运行完整演示
   */
  runFullDemo() {
    if (this.isRunning) {
      console.warn('演示已在运行中');
      return;
    }

    this.isRunning = true;
    console.log('开始运行完整演示...');

    // 清空场景
    const objects = this.world.getObjects();
    objects.forEach((obj) => {
      this.world.removeObject(obj);
    });

    // 按顺序运行各个演示
    setTimeout(() => this.demoBasicShapes(), 500);
    setTimeout(() => this.demoSelectionAndTransform(), 6000);
    setTimeout(() => this.demoLayerManagement(), 12000);
    setTimeout(() => this.demoUndoRedo(), 18000);
    setTimeout(() => this.demoSerialization(), 24000);

    setTimeout(() => {
      this.isRunning = false;
      console.log('完整演示已完成');
    }, 30000);
  }

  /**
   * 事件处理函数
   */
  onObjectAdded({ object }) {
    console.log(`对象已添加: ${object.type} (${object.id})`);
  }

  onObjectRemoved({ object }) {
    console.log(`对象已移除: ${object.type} (${object.id})`);
  }

  onSelectionChanged({ selected }) {
    console.log(`选择变化: ${selected.length} 个对象被选中`);
  }

  onTransformChanged({ objects }) {
    console.log(`变换完成: ${objects.length} 个对象被变换`);
  }

  onViewChanged({ transform }) {
    console.log('视图已变化:', transform);
  }

  onHistoryChanged() {
    const canUndo = this.world.canUndo();
    const canRedo = this.world.canRedo();
    console.log(`历史记录变化 - 可撤销: ${canUndo}, 可重做: ${canRedo}`);
  }

  onLayerChanged() {
    const layers = this.world.getAllLayers();
    const activeLayer = this.world.getActiveLayer();
    console.log(
      `图层变化 - 总图层数: ${layers.length}, 活动图层: ${activeLayer?.name}`,
    );
  }

  /**
   * 获取World实例
   */
  getWorld() {
    return this.world;
  }

  /**
   * 销毁演示
   */
  destroy() {
    if (this.world) {
      this.world.destroy();
    }
    this.isRunning = false;
    console.log('2D World 演示已销毁');
  }
}

/**
 * 快速启动函数
 */
export function createDemo(canvasElement) {
  return new WorldDemo(canvasElement);
}

/**
 * 便捷的演示启动函数
 */
export function startQuickDemo(canvasElement) {
  const demo = new WorldDemo(canvasElement);

  // 延迟启动演示，确保World已完全初始化
  setTimeout(() => {
    demo.demoBasicShapes();

    // 自动运行选择变换演示
    setTimeout(() => {
      demo.demoSelectionAndTransform();
    }, 5000);
  }, 1000);

  return demo;
}

// 如果直接在浏览器中运行，自动创建演示
if (typeof window !== 'undefined') {
  window.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('worldCanvas');
    if (canvas) {
      console.log('检测到canvas元素，自动创建演示...');
      const demo = startQuickDemo(canvas);

      // 将demo实例挂载到window，方便调试
      window.worldDemo = demo;
    }
  });
}
